﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace UDPKeyboard
{
    static class SendKey
    {

        [DllImport("User32.dll")]
        static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);

        [StructLayout(LayoutKind.Explicit)]
        struct INPUT
        {
            [FieldOffset(0)]
            public uint type;
            [FieldOffset(4)]
            public MOUSEINPUT mi;
            [FieldOffset(4)]
            public KEYBDINPUT ki;
        }

        [StructLayout(LayoutKind.Sequential)]
        struct MOUSEINPUT
        {
            public int dx;
            public int dy;
            public uint mouseData;
            public uint dwFlags;
            public uint time;
            public IntPtr dwExtraInfo;
        }

        [StructLayout(LayoutKind.Sequential)]
        struct KEYBDINPUT
        {
            public ushort wVk;
            public ushort wScan;
            public uint dwFlags;
            public uint time;
            public IntPtr dwExtraInfo;
        }

        enum InputType
        {
            INPUT_MOUSE = 0,
            INPUT_KEYBOARD = 1,
            INPUT_HARDWARE = 2
        }

        enum KeyFlags
        {
            EXTENDEDKEY = 0x0001,
            KEYUP = 0x0002,
            KEYDOWN = 0x0000,
            UNICODE = 0x0004,
            SCANCODE = 0x0008
        }

        public static void KeyPress(ushort key, bool keyDown)
        {
            INPUT structInput = new INPUT();
            structInput.type = (int)InputType.INPUT_KEYBOARD;
            structInput.ki.dwFlags = (uint)KeyFlags.SCANCODE;
            if (!keyDown) structInput.ki.dwFlags += (uint)KeyFlags.KEYUP;
            structInput.ki.wScan = key;
            SendInput(1, ref structInput, Marshal.SizeOf(structInput));
        }
    }
}
